<template>
    <div>
        <el-row>
            <el-tabs
                v-loading="isLoading"
                v-model="typeActiveTab"
                type="card"
            >
                <el-tab-pane
                    label="基本信息"
                    name="tabBase"
                    v-if="!isLoading"
                >
                    <base-info
                        ref="baseInfoForm"
                        :isAdvancedSetting="isAdvancedSetting"
                        :diagnosis="diagnosis"
                    ></base-info>

                    <el-row
                        type="flex"
                        justify="center"
                        style="margin-top: 20px"
                    >
                        <el-button
                            @click="diagnosisDialogSave"
                            type="primary"
                            size="mini"
                        >
                            保存
                        </el-button>
                        <el-button
                            @click="diagnosisAssign(diagnosis.id)"
                            type="primary"
                            size="mini"
                        >
                            分配
                        </el-button>
                        <el-button
                            @click="goBack"
                            size="mini"
                        >
                            返回
                        </el-button>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane
                    label="病理信息"
                    name="tabPathologyInfo"
                    v-if="!isLoading"
                >
                    <pathology-info :diagnosis="diagnosis"></pathology-info>

                    <el-row
                        type="flex"
                        justify="center"
                        style="margin-top: 20px"
                    >
                        <el-button
                            @click="diagnosisDialogSave"
                            type="primary"
                            size="mini"
                        >
                            保存
                        </el-button>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane
                    label="病理切片"
                    name="tabPathologyList"
                    v-if="!isLoading"
                >
                    <span slot="label">病理切片
                        <el-badge
                            v-if="pathologicalCount > 0"
                            :value="pathologicalCount"
                            class="tab-content-badge"
                        ></el-badge>
                    </span>
                    <pathology-list :diagnosis="diagnosis"></pathology-list>
                </el-tab-pane>
                <el-tab-pane
                    label="诊断意见"
                    name="tabOpinion"
                    v-if="!isLoading"
                >
                    <opinion
                        :diagnosis="diagnosis"
                        @diagnosisRequest="diagnosisRequest"
                        @diagnosisSearch="diagnosisSearch"
                    ></opinion>
                </el-tab-pane>
                <el-tab-pane
                    label="附件资料"
                    name="tabAttachment"
                    v-if="!isLoading"
                >
                    <attachment
                        :data="diagnosis.attachment"
                        :diagnosis-id="diagnosis.id"
                    ></attachment>
                </el-tab-pane>
                <el-tab-pane
                    label="讨论留言"
                    name="tabDiscussion"
                    v-if="!isLoading"
                >
                    <discussion
                        :messageList="diagnosis.messageBoardList"
                        :isTheseDoctor="isTheseDoctor"
                        :doctorList="doctorList"
                    ></discussion>
                </el-tab-pane>
            </el-tabs>
        </el-row>

        <el-dialog
            :close-on-click-modal="false"
            title="分配专家"
            :visible.sync="doctorsDialog.visible"
            width="90%"
        >
            <base-table
                v-loading="!doctorsTable.isReady"
                ref="doctorsTable"
                :data="doctorsTable.data"
                :header="doctorsTable.header"
                :operation="doctorsTable.operation"
                :pageInfo="doctorsTable.pageInfo"
                @handleClick="doctorsTableButtonClick"
                @pageJumpTo="doctorsTablePageJumpTo"
                @sizeChange="doctorsTableSizeChange"
            >
            </base-table>
            <el-row
                style="margin-top: 10px"
                type="flex"
                justify="end"
            >
                <el-button
                    @click="doctorsDialog.visible = false"
                    size="mini"
                >取消</el-button>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash';
import diagnosisDefaultBase from '@templates/diagnosisDefault';
import BaseTable from '@templates/components/BaseTable';
import BaseInfo from './DiagnosisMatchDetailBase';
import PathologyInfo from './DiagnosisMatchDetailPathologyInfo';
import PathologyList from './DiagnosisDetailPathologyList';
import Opinion from './DiagnosisDetailOpinion';
import Attachment from './DiagnosisDetailAttachment';
import Discussion from './diagnosisDetailDiscussion';
import { itemsPerPage } from '@/client/libs/util';

const changeKeyListDefault = [
    'patientId',
    'checkCategory',
    'patientCategory',
    'name',
    'age',
    'sex',
    'ageUnit',
    'cardId',
    'wardName',
    'bedId',
    'sampleBody',
    'sampleOrganId',
    'sendDoctor',
    'sendDepartment',
    'sendDoctorTel',
    'specimenName',
    'specimenType',
    'specimenRegisterTime',

    'needFirstVisit',
    'needSkipSubmit',
    'canFinalVerify',

    'pathologySummary',
    'pathologyClinicalDiagnosis',
    'pathologyObserved',
    'pathologyDiagnosis',
    'pathologyMolecular',
    'pathologyImmunology',
];

const diagnosisDefault = _.clone(diagnosisDefaultBase);
diagnosisDefault.previousPathologyId = '';
diagnosisDefault.nextPathologyId = '';
diagnosisDefault.collectionId = 0;

export default {
    name: 'DiagnosisDetail',

    components: {
        BaseInfo,
        BaseTable,
        PathologyInfo,
        PathologyList,
        Opinion,
        Attachment,
        Discussion,
    },

    data() {
        return {
            //病理切片角标
            pathologicalCount: 0,

            diagnosis: diagnosisDefault,
            diagnosisClone: diagnosisDefault,
            changeKeyList: changeKeyListDefault,
            typeActiveTab: 'tabBase',
            isLoading: true,
            diagnosisIdBak: '',
            pathologyIdBak: '',
            isAdvancedSetting: false,
            doctorsTable: {
                isReady: false,
                data: [],
                header: [
                    {
                        label: '姓名',
                        prop: 'name',
                        width: '80',
                    },
                    {
                        label: '医生职称',
                        prop: 'positionName',
                        width: '150',
                    },
                    {
                        label: '医生职级',
                        prop: 'medicalTitleName',
                        width: '150',
                    },
                    {
                        label: '所属医院',
                        prop: 'institutionName',
                    },
                    {
                        label: '医生擅长',
                        prop: 'major',
                    },
                ],
                operation: [
                    {
                        label: '分配',
                        functionKey: 'doctorsTableAssign',
                    },
                ],
                pageInfo: {
                    page: 1,
                    size: itemsPerPage.get(),
                    total: 0,
                },
            },
            doctorsDialog: {
                visible: false,
            },
        };
    },
    async mounted() {
        await this.diagnosisRequest();
    },
    computed: {
        doctorList() {
            const list = [];
            this.diagnosis.diagnosisDetailList.forEach((t) => {
                list.push({
                    id: t.doctorId,
                    level: t.currentLevel,
                    name: t.doctorName,
                });
            });
            return list;
        },
        isTheseDoctor() {
            const { state } = this.$store;
            const userId = state.user.id;
            return this.doctorList.some((t) => t.id === userId);
        },
    },
    methods: {
        async diagnosisRequest() {
            this.isLoading = true;
            const { state } = this.$store;
            const { pathologyId } = state.diagnosis;
            const res = await this.$axios({
                method: 'GET',
                url: '/PROXY-Remote/diagnosis/single',
                params: { pathologyId },
            });
            try {
                if (res && res.data.code !== 200) {
                    this.$message.warning('未找到该诊断');
                    // 如果新的诊断找不到，则重新查找旧诊断
                    if (pathologyId !== this.pathologyIdBak) {
                        this.$store.commit('setPropertyGeneral', {
                            key: 'diagnosis',
                            value: {
                                id: this.diagnosisIdBak,
                                pathologyId: this.pathologyIdBak,
                            },
                        });
                        this.diagnosisRequest();
                    } else {
                        throw new Error(res.data);
                    }
                    this.isLoading = false;
                } else {
                    this.isLoading = true;
                    const result = res.data.data;
                    this.pathologicalCount = res.data.data.biopsyList.length;
                    // 更新 id 和病理编号的备份
                    this.diagnosisIdBak = result.id;
                    this.pathologyIdBak = pathologyId;
                    this.$store.commit('setPropertyGeneral', {
                        key: 'diagnosis',
                        value: {
                            id: result.id,
                            pathologyId,
                        },
                    });
                    Object.keys(this.diagnosis).forEach((key) => {
                        if (typeof this.diagnosis[key] === 'string') {
                            this.diagnosis[key] = _.get(result, key, '');
                        } else if (typeof this.diagnosis[key] === 'number') {
                            this.diagnosis[key] = _.get(result, key, 0);
                        } else if (this.diagnosis[key] instanceof Array) {
                            this.diagnosis[key] = _.clone(result[key]);
                        } else if (this.diagnosis[key] instanceof Object) {
                            this.diagnosis[key] = _.get(result, key, {
                                name: '',
                            });
                        } else {
                            this.diagnosis[key] = _.get(result, key, '');
                        }
                        this.diagnosis.attachment = result.attachmentList;
                        if (this.diagnosis[key] === null) {
                            this.diagnosis[key] = '';
                        }
                    });

                    // 取材脏器名字获取
                    this.diagnosis.sampleOrganName = _.get(
                        this.diagnosis.sampleOrganOrgan,
                        'name',
                        ''
                    );
                    this.diagnosis.ageAll = `${this.diagnosis.age}${this.diagnosis.ageUnitName}`;
                    this.diagnosis.diagnosisDetailList.forEach((t, index) => {
                        if (t.detailString) {
                            const detailString = t.detailString.replace(
                                '\\',
                                ''
                            );
                            this.diagnosis.diagnosisDetailList[
                                index
                            ].detailJson = JSON.parse(detailString);
                        } else {
                            this.diagnosis.diagnosisDetailList[
                                index
                            ].detailJson = {};
                        }
                    });

                    // 调用副本
                    this.diagnosisClone = _.clone(this.diagnosis);
                    this.isLoading = false;
                }
            } catch (e) {
                console.log('happened');
                this.$message.warning('请求失败');
                this.isLoading = false;
            }
        },

        diagnosisSearch(pathologyId) {
            console.log('diagnosisSearch', pathologyId);
            this.$store.commit('setPropertyGeneral', {
                key: 'diagnosis',
                value: {
                    pathologyId,
                },
            });
            this.diagnosisRequest();
        },
        async diagnosisDialogSave() {
            this.$refs.baseInfoForm
                .validateForm()
                .then(async () => {
                    // 保留变更的字段，去除未修改的字段
                    // 对于三个诊断设置字段，修改脏器时会默认更新这些字段，若手动变更了该值则以手动设置的值为准
                    const diagnosisTemp = {
                        id: this.diagnosis.id,
                    };
                    this.changeKeyList.forEach((key) => {
                        if (this.diagnosisClone[key] !== this.diagnosis[key]) {
                            diagnosisTemp[key] = this.diagnosis[key];
                        }
                    });
                    diagnosisTemp.cardId = Base64.encode(diagnosisTemp.cardId);
                    // 诊断三项高级设置处理
                    if (!this.isAdvancedSetting) {
                        delete diagnosisTemp.needFirstVisit;
                        delete diagnosisTemp.needSkipSubmit;
                        delete diagnosisTemp.canFinalVerify;
                    } else {
                        diagnosisTemp.needFirstVisit =
                            this.diagnosis.needFirstVisit;
                        diagnosisTemp.needSkipSubmit =
                            this.diagnosis.needSkipSubmit;
                        diagnosisTemp.canFinalVerify =
                            this.diagnosis.canFinalVerify;
                    }

                    const res = await this.$axios({
                        method: 'PUT',
                        url: `/PROXY-Remote/diagnosis/${diagnosisTemp.id}`,
                        data: diagnosisTemp,
                    });

                    if (res && res.data.code === 200) {
                        // 为确保数据一致性与其他标签页不变动，仅复制到Clone
                        this.diagnosisClone = _.clone(this.diagnosis);
                        this.$message.success('保存成功');
                    }
                })
                .catch(() => {
                    this.$message.warning('请填写正确的信息');
                });
        },
        // 分配
        async diagnosisAssign(diagnosisId) {
            this.doctorsDialogOpen(diagnosisId);
        },
        // 分配医生对话框 - 打开
        doctorsDialogOpen(diagnosisId) {
            this.doctorsTable.pageInfo.page = 1;
            this.doctorsDialog.visible = true;
            this.doctorsTableDataGet(diagnosisId);
        },
        // 获取分配专家
        async doctorsTableDataGet(diagnosisId) {
            const id = diagnosisId;
            this.doctorsTable.isReady = false;

            const res = await this.$axios({
                method: 'get',
                url: `/PROXY-Remote/diagnosis/${id}/next-flow-doctors`,
                params: {
                    page: this.doctorsTable.pageInfo.page - 1,
                    size: this.doctorsTable.pageInfo.size,
                },
            });

            if (res && res.data.code === 200) {
                const result = res.data;
                this.doctorsTable.pageInfo = {
                    total: result.pageInfo.total,
                    page: result.pageInfo.page + 1,
                    size: result.pageInfo.size,
                };
                // this.doctorsTable.pageInfo.hide = true;

                this.doctorsTable.data = [];
                result.data.forEach((element) => {
                    this.doctorsTable.data.push(element);
                });
                this.doctorsTable.isReady = true;
            } else {
                this.$message.warning('请求失败');
                this.doctorsTable.isReady = true;
            }
        },
        doctorsTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        doctorsTablePageJumpTo(val) {
            this.doctorsTable.pageInfo.page = val;
            this.doctorsTableDataGet();
        },
        doctorsTableSizeChange(val) {
            this.doctorsTable.pageInfo.size = val;
            this.doctorsTableDataGet();
        },
        diagnosisTableButtonVisibleFunc(functionKey, row) {
            switch (functionKey) {
                case 'diagnosisAssign':
                    return row.currentLevel === 1;
                case 'diagnosisReassign':
                    return row.currentLevel !== 1 && row.currentLevel !== 6;
                default:
                    return true;
            }
        },
        doctorsTableAssign(currentRowDocTor) {
            this.$confirm(`分配给${currentRowDocTor.name}`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    const level = _.get(currentRowDocTor, 'nextFlowLevel', 0);
                    if (!level) {
                        this.$message.info('分配失败');
                        return;
                    }

                    const res = await this.$axios({
                        method: 'put',
                        url: `/PROXY-Remote/diagnosis/${this.diagnosis.id}/next-flow`,
                        data: {
                            doctorId: currentRowDocTor.id,
                            isTempStorage: 0,
                            level,
                        },
                        headers: {
                            'Content-Type': 'application/json',
                        },
                    });

                    if (res && res.data.code === 200) {
                        this.$message.info('分配成功');
                        this.doctorsDialog.visible = false;
                        this.diagnosisTableRequest();
                    } else {
                        this.$message.info('分配失败');
                    }
                })
                .catch(() => {});
        },
        goBack() {
            this.$router.go(-1);
        },
    },
};
</script>

<style scoped>
</style>
